﻿using System.Collections.Generic;
using System.Web.Routing;
using DreamStore.WebShop.Extensibility;
using DreamStore.WebShop.ViewModels;
using Orchard.Environment.Extensions;

namespace DreamStore.WebShop.Services
{
    [OrchardFeature("DreamStore.WebShop.PayPalPSP")]
    public class PayPalPaymentServiceProvider : IPaymentServiceProvider
    {
        public void RequestPayment(PaymentRequest request)
        {
            var rvd = new RouteValueDictionary
                                  {
                                      {"action", "RedirectToPayPal"},
                                      {"controller", "PayPal"},
                                      {"area", "DreamStore.WebShop"},
                                      {"orderReference", request.Order.Number},
                                  };
            //request.ActionResult = new RedirectToRouteResult(rvd);
            request.WillHandlePayment = true;
            request.PaymentServiceProviderViewModels.Add(new PaymentServiceProviderViewModel
            {
                ProviderName = "PayPal",
                ImageName = "paypal.jpg",
                RouteValues = rvd,
            });
        }

        public void ProcessResponse(PaymentResponse response)
        {
            if (response.WillHandleResponse)
            {
                return;
            }
            var result = response.HttpContext.Request.QueryString["result"];
            response.OrderReference = response.HttpContext.Request.QueryString["orderReference"];
            response.PaymentReference = response.HttpContext.Request.QueryString["paymentId"];
            response.ResponseText = response.HttpContext.Request.QueryString.ToString();
            switch (result)
            {
                case "PayPalOk":
                    response.Status = PaymentResponseStatus.Success;
                    response.WillHandleResponse = true;
                    break;

                case "PayPalNoGo":
                    response.Status = PaymentResponseStatus.Failed;
                    response.WillHandleResponse = true;
                    break;

                default:
                    response.WillHandleResponse = false;
                    break;
            }
            
        }
    }
}